package com.sup.generator.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.sup.generator.config.GrRedisPrefixConfig;
import com.sup.generator.exception.GrException;
import com.sup.generator.fixedvalue.GrMessage;
import com.sup.generator.service.GrRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;

/**
 * @author Zh
 * @version v1.0
 * @description:
 * @date 2020/11/13 19:30
 */
@Service("grRedisServiceImp")
public class GrRedisServiceImp implements GrRedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 写入数据
     * @param userId
     * @param prefixConfig
     * @param data
     */
    @Override
    public void setString(Long userId, GrRedisPrefixConfig prefixConfig, Object data) {
        if("".equals(userId) || "".equals(data)){
            throw new GrException(GrMessage.DATA_NULL);
        }
        String dataStr = JSONObject.toJSONString(data);
        String newKey = String.format("%s_%s",prefixConfig.getPrefix(),userId);
        Long second = prefixConfig.getSeconds();
        if("0".equals(second)){
            redisTemplate.opsForValue().set(newKey, dataStr);
        }
        redisTemplate.opsForValue().set(newKey, dataStr, second);
    }

    /**
     * 读取数据
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    @Override
    public <T>T get(String key, Class clazz) {
        if("".equals(key)){
            throw new GrException(GrMessage.DATA_NULL);
        }
        Object resultObject = redisTemplate.opsForValue().get(key);
        return JSONObject.parseObject(JSONObject.toJSONString(resultObject), (Type) clazz);
    }

    /**
     * 删除数据
     * @param userId
     * @param prefixConfig
     */
    @Override
    public Boolean remove(Long userId, GrRedisPrefixConfig prefixConfig) {
        if("".equals(userId)){
            throw new GrException(GrMessage.DATA_NULL);
        }
        String newKey = String.format("%s_%s",prefixConfig.getPrefix(),userId);
        return redisTemplate.delete(newKey);
    }
}
